
//
//  UserRealVideoController.m
//  CheekiOS
//
//  Created by mac on 2017/6/20.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserRealVideoController.h"
#import <AVFoundation/AVFoundation.h>
@interface UserRealVideoController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,CAAnimationDelegate>
/** vedioImageV*/
@property (nonatomic, strong) UIImageView *videoImage;
/** 视频路径*/
@property (nonatomic, strong) NSURL *vedioUrl;
/** 视频View */
@property (nonatomic, strong) UIView *PlayerView;
@property (nonatomic, strong) AVPlayer *player ;
@property (nonatomic, strong) AVPlayerLayer *playerLayer ;

@property (nonatomic, strong) UIButton *btnUpdate;//上传

@property (nonatomic, strong) UserpersionlInfoModel *userInfoModel;//个人信息

@property (nonatomic, assign) BOOL UpdateVideo;//判断视频时候改变，如果改变上传，如果不变唤出alert

@end

@implementation UserRealVideoController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavgationBarHiddenNo];
    [self requestUserInfo];
    self.view.backgroundColor =[UIColor whiteColor];
    self.title = @"视频认证";
    
    _videoImage =[[UIImageView alloc]init];
//    imgView.contentMode = UIViewContentModeScaleAspectFill;
    _videoImage.frame = CGRectMake(KScreenWidth/2-KScreenWidth/4, 60, KScreenWidth/2, KScreenWidth/2);

    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pickVedio)];
    [_videoImage addGestureRecognizer:tap];
    _videoImage.userInteractionEnabled = YES;
    
    [self.view addSubview:_videoImage];

    UILabel *promptLab = [[UILabel alloc]init];
    
    promptLab.font = FontP(16);
    
    promptLab.text = @"贴脸儿是真实高效的全民技能邀约平台为保证用户真实性，以及邀约见面的安全与高效，我们通过一段您本人的真实视频来拒绝虚假！\n视频认证每天只可上传认证一次";
    promptLab.numberOfLines = 0;
    CGSize promptLabSize = textSizeFont(promptLab.text, promptLab.font, KScreenWidth, KScreenHeight);
    promptLab.frame = CGRectMake(36.5, _videoImage.bottom+30, KScreenWidth-73, promptLabSize.height);
    [self.view addSubview:promptLab];
    
    _btnUpdate = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnUpdate.frame = CGRectMake(self.view.centerX-50, promptLab.bottom+80*SCREEN_WIDTH_RATIO55, 100*SCREEN_WIDTH_RATIO55, 100*SCREEN_WIDTH_RATIO55);
  
    [_btnUpdate setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_btnUpdate setTitle:@"点击上传" forState:UIControlStateNormal];
    _btnUpdate.backgroundColor = Colorbackground;
    _btnUpdate.layer.cornerRadius=50;
    _btnUpdate.titleLabel.font = FontP(15);
    [_btnUpdate addTarget:self action:@selector(commitClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:_btnUpdate];

    [self requestUserInfo];
    
}

-(void)requestUserInfo{

    [HcardHttpmanager getPersionalUserInfosuccess:^(id sucess) {
        
        if (sucess) {
            self.userInfoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];

            if (self.userInfoModel.videoImg.length>0) {
                [self.videoImage sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(self.userInfoModel.videoImg)] placeholderImage:[UIImage imageNamed:@"llustration"]];
                self.vedioUrl = [NSURL URLWithString:HttpImgUrl(self.userInfoModel.video)];
                _UpdateVideo =YES;

            }else{
                self.videoImage.image = [UIImage imageNamed:@"p_center_sprz_tv"];

            }
        }
        

        
        
        
        
    } failure:^(NSError *error) {
        
    }];
    
}

-(void)pickVedio{
    
 
    
    if(self.vedioUrl){
        self.view.window.backgroundColor = [UIColor whiteColor];

        _PlayerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        _PlayerView.backgroundColor = [UIColor blackColor];
        
        CABasicAnimation *animation = nil;
        //缩放
        animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [animation setFromValue:@0.1];//设置起始值
        [animation setToValue:@1.];//设置目标值
        [animation setDelegate:self];//代理回调
        [animation setDuration:0.3];//设置动画时间，单次动画时间
        [animation setRemovedOnCompletion:NO];
        
        //you view need to replace
        [_PlayerView.layer addAnimation:animation forKey:nil];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.frame = _PlayerView.frame;
        [btn addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat Height = KScreenWidth/4*3;
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:_vedioUrl];
        AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item];
        AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer: player];
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        playerLayer.frame = CGRectMake(0, -64, KScreenWidth, Height+64);
        playerLayer.position = self.view.center;
        
        [_PlayerView.layer addSublayer: playerLayer];
        [playerLayer setNeedsDisplay];
        
        [player play];
        
        self.player = player;
        
        _playerLayer = playerLayer;
        
        
        __weak typeof(self) weakSelf = self;
        NSNotificationCenter *noteCenter = [NSNotificationCenter defaultCenter];
        [noteCenter addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
                                object:nil
                                 queue:nil
                            usingBlock:^(NSNotification *note) {
                                [weakSelf.player seekToTime:kCMTimeZero];
                                [weakSelf.player play];
                            }];
        [_PlayerView addSubview:btn];
        [self.view.window addSubview:_PlayerView];

        
    
    }else{

        [self tapClick];
    }

}

-(void)commitClick:(UIButton *)sender{
    

    if (_UpdateVideo == YES) {
        [self tapClick];
        return ;

    }
    
    

    if(!self.vedioUrl){
        [SVProgressHUD showInfoWithStatus:@"请先选择视频"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
            
        });
        [self tapClick];
        return ;
    }
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"视频认证每天只可上传认证一次！" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        sender.userInteractionEnabled = NO;
        [SVProgressHUD showWithStatus:@"正在上传"];
        if(self.vedioUrl){
            [HcardHttpmanager upLoadVideoVideoPath:self.vedioUrl WithBelong:@"identifyVedioYD" uploadSuccess:^(id sucess) {
                if(sucess){
                    [SVProgressHUD dismiss];
                    [SVProgressHUD showSuccessWithStatus:@"上传成功，正在审核"];
                    NSString *url = sucess;
                    [HQHttpManager updateUserWithUid:nil mobile:nil photo:nil motto:nil sex:nil nickName:nil birthday:nil animal:nil height:nil weight:nil affection:nil email:nil job:nil hometown:nil activeSite:nil skill:nil wantSkill:nil zfb:nil zfbName:nil cardImg:nil video:url privacy:nil isShield:nil successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                        sender.userInteractionEnabled = YES;
                        if (isSuccess) {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                
                                [self.navigationController popViewControllerAnimated:YES];
                                [SVProgressHUD dismiss];

                            });
                        }
                    }];
                }
                else{
                    [SVProgressHUD showErrorWithStatus:@"上传失败!"];
                    sender.userInteractionEnabled = YES;
                    
                }
                
            } uploadFailure:^(NSError *failure) {
                [SVProgressHUD showErrorWithStatus:@"上传失败!"];
                sender.userInteractionEnabled = YES;
                
            } progress:^(NSProgress *progress) {
                
            }];
            

        }else{
            [SVProgressHUD dismiss];
        }

        
    }];
    UIAlertAction *cliceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:confirAction];
    [alertVC addAction:cliceAction];
    [self.navigationController presentViewController:alertVC animated:YES completion:nil];
    
    
}



- (void)backButtonClick{
    [_player pause];
    _player = nil;
    CABasicAnimation *animation = nil;
    //缩放
    animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    [animation setFromValue:@1.0f];//设置起始值
    [animation setToValue:@0.1f];//设置目标值
    [animation setDelegate:self];//代理回调
    [animation setDuration:0.3f];//设置动画时间，单次动画时间
    [animation setRemovedOnCompletion:NO];
    
    //you view need to replace
    [_PlayerView.layer addAnimation:animation forKey:nil];
    
    [UIView animateWithDuration:0.3f animations:^{
        
        
    } completion:^(BOOL finished) {
        [self.view.window removeFromSuperview];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _PlayerView.hidden = YES;
            
            [_PlayerView removeFromSuperview];
            self.view.backgroundColor = [UIColor whiteColor];
        });
        
    }];
    
    
}
#pragma mark - tapClick
-(void)tapClick{
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择视频" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeSavedPhotosAlbum)] && [UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
            picker.mediaTypes = temp_MediaTypes;
            picker.videoQuality = UIImagePickerControllerQualityTypeHigh;//视频质量设置
//            UIImagePickerControllerQualityTypeHigh = 0,       // highest quality
//            UIImagePickerControllerQualityTypeMedium = 1,     // medium quality, suitable for transmission via Wi-Fi
//            UIImagePickerControllerQualityTypeLow = 2,         // lowest quality, suitable for tranmission via cellular network
//            UIImagePickerControllerQualityType640x480 NS_ENUM_AVAILABLE_IOS(4_0) = 3,    // VGA quality
//            UIImagePickerControllerQualityTypeIFrame1280x720 NS_ENUM_AVAILABLE_IOS(5_0) = 4,
//            UIImagePickerControllerQualityTypeIFrame960x540 NS_ENUM_AVAILABLE_IOS(5_0) = 5,

            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            picker.videoMaximumDuration = 10.0;
            picker.delegate = self;
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            picker.mediaTypes = @[(NSString *)kUTTypeMovie];
            [self presentViewController:picker animated:YES completion:NULL];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:^{
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];//视频路径
        NSString *urlStr=[url path];
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
            self.vedioUrl = url;
            UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);//保存视频到相簿
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

//视频保存后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"视频错误，请重新拍摄或重新选择"];
    }else{
//        self.videoImage.contentMode = UIViewContentModeScaleAspectFill;
        _UpdateVideo = NO;
        self.videoImage.image = [HcardHttpmanager thumbnailImageForVideo:self.vedioUrl atTime:0.5];

    }
}



@end
